package org.example.system.controller;

import org.example.system.entity.Order;
import org.example.system.service.OrderService;
import org.example.system.service.ScenicSpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ScenicSpotService scenicSpotService;

    @GetMapping
    public List<Order> list(@RequestParam(required = false) String username,
                            @RequestParam(required = false) String product,
                            @RequestParam(required = false) String location,
                            @RequestParam(required = false) Integer quantity) {
        return orderService.findByCondition(username, product, location, quantity);
    }

    @GetMapping("/{id}")
    public Order detail(@PathVariable Long id) {
        return orderService.findById(id);
    }

    @PostMapping
    public Map<String, Object> add(@RequestBody Order order) {
        Map<String, Object> result = new HashMap<>();
        int row = orderService.add(order);
        if (row > 0) {
            // 下单成功，减少库存
            scenicSpotService.decreaseStockByName(order.getLocation(), order.getQuantity());
        }
        result.put("success", row > 0);
        result.put("message", row > 0 ? "添加成功" : "添加失败");
        return result;
    }

    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody Order order) {
        order.setId(id);
        Map<String, Object> result = new HashMap<>();
        int row = orderService.update(order);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "修改成功" : "修改失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Order order = orderService.findById(id);
        int row = orderService.delete(id);
        if (row > 0 && order != null) {
            // 删除订单，恢复库存
            scenicSpotService.increaseStockByName(order.getLocation(), order.getQuantity());
        }
        result.put("success", row > 0);
        result.put("message", row > 0 ? "删除成功" : "删除失败");
        return result;
    }
} 